# data.explorer模块
from typing import Annotated 
from sqlite3 import IntegrityError, Error

from fastapi import Depends 
from .database import create_curs
from model.explorer import Explorer 
from error import Missing, Duplicate 


def row_to_model(row): 
    name, country, description = row 
    return Explorer(name=name, country=country, description=description)


def create_table(): 
    with create_curs() as curs: 
        curs.execute("""create table if not exists explorer(
                        name text primary key, 
                        country text, 
                        description text
                     )""")

def get_one(name: str) -> Explorer: 
    qry = 'select * from explorer where name = :name'
    params = {'name': name}
    with create_curs() as curs: 
        
        curs.execute(qry, params)
        row = curs.fetchone()
        if not row: 
            raise Missing(f'Explorer {name} not found')

        return row_to_model(row)
    
    

def get_all() -> list[Explorer]: 
    qry = 'select * from explorer' 
    with create_curs() as curs: 
        curs.execute(qry)
        rows = curs.fetchall()
    if not rows: 
        raise Missing(f'Explorer: not found ')
    return [row_to_model(row) for row in rows]


def create(explorer: Explorer) -> Explorer: 
   
    qry = 'insert into explorer(name, country, description) values ' \
          '(:name, :country, :description)'
    
    params = explorer.model_dump()
    with create_curs() as curs: 
        try:
            curs.execute(qry, params)

        except IntegrityError as e :
            
            raise Duplicate(f'Explorer {explorer.name} already exists {e.sqlite_errorname}')
        
    return get_one(explorer.name)


def modify(name: str, explorer: Explorer) -> Explorer: 
    
    get_one(name)

    qry = 'update explorer ' \
            'set name = :name,' \
            'country = :country, ' \
            'description = :description' \
            ' where name = :name_orig'
    
    params = explorer.model_dump()
    params['name_orig'] = name 

    with create_curs() as curs: 
        try:
            curs.execute(qry, params)
        except IntegrityError: 
            raise Duplicate(f'Explorer: {explorer.name} is exists.')
    return get_one(explorer.name)

    

def delete(name: str): 
    get_one(name)

    qry = 'delete from explorer where name = :name'
    params = {'name': name}
    with create_curs() as curs: 
        
        curs.execute(qry, params)
         
create_table()

